<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索用户昵称"
              style="width: 200px; margin-right: 10px;"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="userList" v-loading="loading" stripe>
        <el-table-column prop="nickName" label="昵称" min-width="120" />
        
        <el-table-column prop="openid" label="OpenID" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="phoneNumber" label="手机号" min-width="150">
          <template #default="scope">
            {{ scope.row.phoneNumber ? maskPhone(scope.row.phoneNumber) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button 
              size="small" 
              :type="getStatusButtonType(scope.row.status)"
              @click="handleChangeStatus(scope.row)"
            >
              {{ getStatusButtonText(scope.row.status) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="昵称">
            {{ selectedUser.nickName }}
          </el-descriptions-item>
          <el-descriptions-item label="OpenID">
            {{ selectedUser.openid }}
          </el-descriptions-item>
          
          <el-descriptions-item label="手机号">
            {{ selectedUser.phoneNumber ? maskPhone(selectedUser.phoneNumber) : '-' }}
          </el-descriptions-item>
          
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedUser.status)">
              {{ getStatusText(selectedUser.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="余额">
            {{ selectedUser.balance || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="会员等级">
            {{ selectedUser.memberLevel || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="总消费">
            {{ selectedUser.totalConsumption || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDate(selectedUser.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatDate(selectedUser.lastLoginTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 用户活动参与记录 -->
        <div class="user-activities" style="margin-top: 20px;">
          <h4>参与活动记录</h4>
          <el-table :data="userActivities" size="small" stripe style="width: 100%">
            <el-table-column prop="activityId" label="活动ID" min-width="180" show-overflow-tooltip />
            <el-table-column prop="registrationTime" label="报名时间" min-width="200">
              <template #default="scope">
                {{ formatDate(scope.row.registrationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag size="small" :type="getActivityStatusType(scope.row.status)">
                  {{ getActivityStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Search, Refresh } from '@element-plus/icons-vue'
import CloudBaseAPI from '@/api/cloudbase'

const userList = ref([])
const loading = ref(false)
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const detailDialogVisible = ref(false)
const selectedUser = ref(null)
const userActivities = ref([])

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const result = await CloudBaseAPI.getUserList(
      currentPage.value, 
      pageSize.value, 
      searchText.value
    )
    
    if (result.success) {
      userList.value = result.data
      total.value = result.total
    } else {
      ElMessage.error(result.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error('获取用户列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 刷新列表
const handleRefresh = () => {
  searchText.value = ''
  currentPage.value = 1
  getUserList()
}

// 页码改变
const handlePageChange = () => {
  getUserList()
}

// 页面大小改变
const handleSizeChange = () => {
  currentPage.value = 1
  getUserList()
}

// 修改用户状态
const handleChangeStatus = async (user) => {
  const targetStatus = user.status === 1 ? 0 : 1
  const action = user.status === 1 ? '禁用' : '启用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.nickName}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const result = await CloudBaseAPI.changeUserStatus(user._id, targetStatus)
    
    if (result.success) {
      ElMessage.success(`${action}成功`)
      getUserList() // 刷新列表
    } else {
      ElMessage.error(result.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
      console.error('修改用户状态错误:', error)
    }
  }
}

// 查看用户详情
const handleViewDetail = async (user) => {
  selectedUser.value = user
  detailDialogVisible.value = true
  
  // 获取用户活动参与记录
  try {
    const result = await CloudBaseAPI.getUserActivities(user.openid)
    if (result.success) {
      userActivities.value = result.data
    }
  } catch (error) {
    console.error('获取用户活动记录错误:', error)
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  selectedUser.value = null
  userActivities.value = []
}

// 手机号加密显示
const maskPhone = (phone) => {
  if (!phone) return ''
  const phoneStr = String(phone)
  if (phoneStr.length !== 11) return phoneStr
  return phoneStr.substring(0, 3) + '****' + phoneStr.substring(7)
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return '-'
    
    // 格式化为：2025-07-29 23:05:12
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    return '-'
  }
}

// 获取用户状态类型
const getStatusType = (status) => {
  return status === 1 ? 'success' : 'danger'
}

// 获取用户状态文本
const getStatusText = (status) => {
  return status === 1 ? '正常' : '禁用'
}

// 获取状态按钮类型
const getStatusButtonType = (status) => {
  return status === 1 ? 'danger' : 'success'
}

// 获取状态按钮文本
const getStatusButtonText = (status) => {
  return status === 1 ? '禁用' : '启用'
}

// 获取活动状态类型
const getActivityStatusType = (status) => {
  const statusMap = {
    'registered': 'success',
    'attended': 'primary',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取活动状态文本
const getActivityStatusText = (status) => {
  const statusMap = {
    'registered': '已报名',
    'attended': '已参加',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.user-detail {
  padding: 10px 0;
}

.user-activities h4 {
  margin-bottom: 10px;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table .cell) {
  word-break: break-all;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>